package com.smw.myrealm;

import com.smw.pojo.User;
import com.smw.service.UserService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.crypto.hash.Sha256Hash;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Set;

public class Myrealm1 extends AuthorizingRealm {
    @Autowired
    private UserService userService;
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("执行了doGetAuthorizationInfo方法，查询用户权限信息的方法") ;

        String name=(String)principalCollection.getPrimaryPrincipal();
        System.out.println("naem:"+name);
        Set<String> roles=userService.findRole(name);
        System.out.println("roles:"+roles);
        SimpleAuthorizationInfo info=new SimpleAuthorizationInfo();
        info.setRoles(roles);

        return info;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        System.out.println("用户登录");
        UsernamePasswordToken token=(UsernamePasswordToken)authenticationToken;

        String userName=(String)token.getPrincipal();
        User u=userService.findPwdByName(userName);
        System.out.println(u);
        if (u==null){
            throw new AuthenticationException();
        }
        SimpleAuthenticationInfo info=new SimpleAuthenticationInfo(
                userName,u.getPassWord(),this.getName()
        );
        return info;
    }
}
